package demo.practice.linklist;

import demo.practice.ListNode;

public class P23_3 {


    public ListNode mergeKLists(ListNode[] lists) {
        if(lists==null || lists.length==0)
            return null;
        return mergeKLists(lists,0,lists.length-1);
    }

    public ListNode mergeKLists(ListNode[] lists, int min, int max) {
        if (min == max) {
            return lists[min];
        }
        int mid = min + (max - min) / 2;
        ListNode befor = mergeKLists(lists, min, mid);
        ListNode behind = mergeKLists(lists, mid + 1, max);
        return mergeTwoLists(befor,behind);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode newhead = new ListNode(0);
        ListNode cur = newhead;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1 != null ? l1 : l2;
        return newhead.next;
    }
}
